import Taro from '@tarojs/taro'
import { genSignature } from '@/utils/auth'
import { loginMethod, goToLogin } from '@/utils/login'

interface Options {
  url: string
  data?: object | string
  header?: object
  method?: 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT'
  dataType?: string
  responseType?: string
  success?: any
  fail?: any
  complete?: any,
  hideLoginModal?: false,
  inHandleError?: false,
  showLoading?: true,
  autoHideLoading?: true
}


const baseUrl = BASE_API_URL
const defConf = {
  url: '',
  header: {
    // 'from':'97WhokCh3wz',
    'content-type': 'application/json'
  },
  hideLoginModal: false,
  inHandleError: false
}

const service = async function (options: Options = defConf) {
  if (options.showLoading) {
    Taro.showLoading({
      title: '加载中',
    })
  }
  let locationInfo = Taro.getStorageSync('CURRENT_LOCATION_INFO') || {}
  let cityCode = locationInfo.adCode ? locationInfo.adCode : ''
  let areaCode = locationInfo.districtCode ? locationInfo.districtCode : ''

  // 加密URL 不能添加域名 先做一下缓存
  let oldUrl = options.url
  //拼接http/https协议
  if (!/^(http|https)/gi.test(options.url)) {
    options.url = baseUrl + options.url
  }
  if (!options.header) {
    options.header = defConf.header
  }
  if (!options.hideLoginModal) {
    options.hideLoginModal = defConf.hideLoginModal
  }
  if (!options.inHandleError) {
    options.inHandleError = defConf.inHandleError
  }
  let thirdPartySource = process.env.TARO_ENV === 'weapp' ? (Taro.getStorageSync('THIRD_PARTY_SOURCE') || 'JEKUNAUTO') : 'JEKUNAUTOALI'
  let clientSource = process.env.TARO_ENV === 'weapp' ? 0 : 9
  if (options.data) {
    const keys = Object.keys(options.data)
    if (keys.includes('cityCode')) {
      cityCode = options.data['cityCode']
    }
    if (keys.includes('areaCode')) {
      areaCode = options.data['areaCode']
    }
    if (options.data.constructor == Object) {
      options.data['thirdPartySource'] = thirdPartySource
      options.data['clientSource'] = clientSource
    }
  }
  if (options.url.indexOf('?') > -1) {
    options.url = options.url + '&thirdPartySource=' + thirdPartySource + '&clientSource=' + clientSource
    oldUrl += '&thirdPartySource=' + thirdPartySource + '&clientSource=' + clientSource
  } else {
    options.url = options.url + '?thirdPartySource=' + thirdPartySource + '&clientSource=' + clientSource
    oldUrl += '?thirdPartySource=' + thirdPartySource + '&clientSource=' + clientSource
  }
  Object.assign(options.header, genSignature({
    method: options.method || 'GET',
    url: oldUrl,
    data: options.data ? options.data : { thirdPartySource: 'JEKUNAUTO', clientSource }
  }), cityCode ? { cityCode } : {}, areaCode ? { areaCode } : {}, clientSource !== '' ? { clientSource } : {}, thirdPartySource ? { thirdPartySource } : {})
  if (process.env.TARO_ENV === 'weapp') { // 微信小程序处理逻辑
    const result = await Taro.request(JSON.parse(JSON.stringify(options)))

    const { statusCode, data } = result
    const { success, data: resData } = data
    if (statusCode === 404) {
      Taro.hideLoading()
      throw statusCode
    }
    // const res = data
    if (!success) {
      Taro.hideLoading()
      if (Taro.getStorageSync('HAS_EXPIRE') == 1) {
        return
      }
      // Taro.hideModal()
      if (statusCode === 406) {
        const authErrorCode = [1003, 1004, 1005, 1006]
        if (authErrorCode.includes(resData.code)) {
          const userInfo = Taro.getStorageSync('IS_USERINFO')
          // 登录失效
          console.log('登录失效了吗')
          console.log('有没有执行到这儿---------------------------------------------------zfb----------------------')
          if (userInfo.accessId) {
            Taro.setStorageSync('HAS_EXPIRE', 1)
            Taro.showModal({
              title: '温馨提示',
              content: '您已经被挤掉，需要重新登录',
              cancelText: '取消',
              cancelColor: '#999999',
              confirmText: '重新登录',
              confirmColor: '#12b3ff',
            }).then(res => {
              // 存起来
              if (res.confirm) {
                // Taro.setStorageSync('IS_SESSIONKEY', null)
                // Taro.setStorageSync('IS_OPENID', null)
                loginMethod()
              }
              Taro.setStorageSync('HAS_EXPIRE', '')
            })
            console.log('登录失效')
          } else {
            Taro.setStorageSync('HAS_EXPIRE', 1)
            console.log('未登录，去登录')
            //禁止弹出登录窗口
            if (options.hideLoginModal) return
            goToLogin()
          }
          return Promise.reject(result)
        }
        // console.log('api错误提示')
        // Taro.showToast({
        //     icon: 'none',
        //     title: resData.message,
        //     duration: 2000
        // })
        // return Promise.reject(result)
      }
      console.log('options.inHandleError', options.inHandleError)
      console.log('错误提示---', resData.message)
      if (!options.inHandleError) {
        Taro.showToast({
          icon: 'none',
          title: resData.message,
          duration: 2000
        })
      }
      return Promise.reject(result)
    }
    if (options.autoHideLoading) {
      Taro.hideLoading()
    }
    return result
  } else if (process.env.TARO_ENV === 'alipay') { // 支付宝小程序处理逻辑
    try {
      let alipayOptions = JSON.parse(JSON.stringify(options))
      if (alipayOptions.data && alipayOptions.data.query) {
        // alipayOptions.data.query = JSON.stringify(alipayOptions.data.query)
      }
      const result = await Taro.request(alipayOptions)
      Taro.hideLoading()
      return result
    } catch (error) {
      console.log('res报错了', error)
      console.log('报错入参-options', options)
      const { status, data } = error
      const { success, data: resData } = data
      if (status === 404) {
        Taro.hideLoading()
        throw status
      }
      // const res = data
      if (!success) {
        Taro.hideLoading()
        if (Taro.getStorageSync('HAS_EXPIRE') == 1) {
          return
        }
        // Taro.hideModal()
        if (status === 406) {
          const authErrorCode = [1003, 1004, 1005, 1006]
          if (authErrorCode.includes(resData.code)) {
            const userInfo = Taro.getStorageSync('IS_USERINFO')
            // 登录失效
            if (userInfo.accessId) {
              Taro.setStorageSync('HAS_EXPIRE', 1)
              Taro.showModal({
                title: '温馨提示',
                content: '您已经被挤掉，需要重新登录',
                cancelText: '取消',
                cancelColor: '#999999',
                confirmText: '重新登录',
                confirmColor: '#12b3ff',
              }).then(res => {
                // 存起来
                if (res.confirm) {
                  loginMethod()
                }
                Taro.setStorageSync('HAS_EXPIRE', '')
              })
              console.log('登录失效')
            } else {
              Taro.setStorageSync('HAS_EXPIRE', 1)
              console.log('未登录，去登录')
              goToLogin()
            }
            return Promise.reject(error)
          }
        }
        console.log('options.inHandleError', options.inHandleError)
        console.log('错误提示---', resData.message)
        if (!options.inHandleError) {
          Taro.showToast({
            icon: 'none',
            title: resData.message,
            duration: 2000
          })
        }
        return Promise.reject(error)
      }
      Taro.hideLoading()
      return error
    }
  }
}

export default service
